package com.ticket.sass.provider.validator;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.ObjectUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDateTime;

/**
 * @author ywb
 * @date 2022-10-09 10:34
 */
public class InTimeValidation implements ConstraintValidator<InTime, Object> {
    
    private String beginTime;
    private String endTime;
    
    @Override
    public void initialize(InTime constraintAnnotation) {
        this.beginTime = constraintAnnotation.beginTime();
        this.endTime = constraintAnnotation.endTime();
    }
    
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        BeanWrapper beanWrapper = new BeanWrapperImpl(value);
        boolean valid = true;
        Object beginValue = beanWrapper.getPropertyValue(beginTime);
        Object endValue = beanWrapper.getPropertyValue(endTime);
        if (!ObjectUtils.isEmpty(beginValue) && !ObjectUtils.isEmpty(endValue)) {
            LocalDateTime beginTimeVal = (LocalDateTime) beginValue;
            LocalDateTime endTimeVal = (LocalDateTime) endValue;
            int result = endTimeVal.compareTo(beginTimeVal);
            if (result < 0) {
                valid = false;
            }
        }
        return valid;
    }
}
